<?php
// +----------------------------------------------------------------------
// | Created by Sublime: [ Conqweal ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~20223[chenjia] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.99dn.cn
// +----------------------------------------------------------------------
// | Author: Conqweal <150672834@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021/12/22 0026
// +----------------------------------------------------------------------
// | Description:rpc远程请求，链接管理系统调用
// +----------------------------------------------------------------------
namespace app\api\controller;
 
use app\api\model\Mission as cModel;
use app\api\model\MissionLinks as linksModel;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Validate; 
use support\Request;
use app\ApiController; 

class Hprose    
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    protected $server      = null;
    protected $crossDomain = true;
    protected $P3P         = true;
    protected $debug       = true;
    //指定扣款用户
    protected $u_id = 1;
    //参考配置文件 
    protected $language_id = 1;
    public function __construct()
    {

        require_once base_path() . "/extend/Hprose/Hprose.php";
        $this->server = new \Hprose\Http\Server();
        $this->server->addInstanceMethods($this);
        $this->server->debug       = $this->debug;
        $this->server->P3P         = $this->P3P;
        $this->server->crossDomain = $this->crossDomain;
    }

    //启动
    public function start()
    {
        $this->server->start();
    }

    public function createMission($v)
    {   
        $time = time();        
        $v['create_time'] = $time; 
        $v['update_time'] = $time; 
        $v['money_cfg'] = ['slt_bid_mode'=>1];            
        $res = $this->createMissionSingle($v);
        if($res['code']>0){
            $links_data = [
                    'mission_id'=>$res['mission_id'],                       
                    'status'=>1,
                    'push_id'=>$v['id'],
                    'links_data'=>$v,                                     
                ];                
            linksModel::create($links_data);
        }      
        return true;

        
    }

    /**
     * 创建单任务
     * @param  [type] $post [description]
     * @return [type]       [description]
     */
    private function createMissionSingle($post){      
        
        $code =0;
        $error = '';
        $mission_id = 0;
        try {            
            $post['u_id'] = $this->u_id;
            $validate     = new \app\api\validate\Mission;             
            $result       = $validate->check($post);
            if (!$result) {
                $error = $validate->getError();
            } else {
                Db::startTrans();
                $cmodel = new cModel;
                //默认不付款 
                $post['status'] = 1;
                $post['remark'] = '系统推送';

                $description = [
                    'language_id' => $this->language_id,
                    'title'       => $post['title'],
                    'content'     => htmlspecialchars($post['content']),
                    'seo'         => $post['seo'],
                ];
                $post['mission_no'] = get_order_sn();

                $data = $cmodel->together(['description' => $description])->save($post);
                if (!$data) {
                    throw new \Exception(__('Operation failed'));
                }
                $mission_id = $cmodel->mission_id;               
                $payed = $this->payForMission($cmodel->mission_id, $cmodel->money);
                $payed && $cmodel->save(['status' => 2]);
                $r  = $cmodel->find($mission_id);              
                if(!$this->checkMoneyCfg($r->money_cfg)){                 
                    throw new \Exception(__('money_cfg参数非法'));
                }
                Db::commit();
                $code = 1;
                $error ='';                

            }
        }catch (\Exception $e) {
            Db::rollback();
           $error = $e->getMessage();
        }
        return ['code'=>$code,'error'=>$error,'mission_id'=>$mission_id,'data'=>$post];

    }



      /**
     * 辅助扣除悬赏付款
     * @return [type] [description]
     */
    private function payForMission($mission_id, $mission_money)
    {
        $balance = \app\api\model\User::where('u_id', $this->u_id)->lock(true)->find();
        $left    = $balance->money - $balance->freeze;
        $payed   = 0;
        
        if ($left >= $mission_money) {
            $balance->dec('money', $mission_money)->update();
            \app\api\model\UserMoneyLog::create([
                'u_id'    => $this->u_id,
                'reduce'  => $mission_money,
                'before'  => $balance->money,
                'after'   => $balance->money - $mission_money,
                'op_type' => 3,
                'op_key'  => $mission_id,
            ]
            );
            $payed = 1;
        }
        return $payed;
    }


     /**
     * 检查金币配置数据合法性
     * @return [type] [description]
     */
    private function checkMoneyCfg($data){
        if(!is_array($data)){
            return false;
        }
        if(!$data['slt_bid_mode']){
            return false;
        }
        return true;
    }




}